//
//  NDOrderContentView.swift
//  NyamanDana
//
//  Created by 李永彬 on 2025/10/25.
//

import SwiftUI

struct NDOrderContentView: View {
    
    let orderTabs: [NDOrderDataType] = [.all, .applying, .repayment, .finish]
    @StateObject private var viewModel = NDOrderListViewModel()
    @StateObject private var refreshController = NDScrollViewRefreshController()
    @Environment(\.navigationManager) var navManager
    
    var body: some View {
        let baseConfig = NDBaseConfig(
            backgroundColor: .clear,
            showNavigationBar: true,
            hiddenTabbar: false
        )
        let navigationConfig = NavigationConfig(
            title: localizedString("list order"),
            showSystemBackButton: false
        )
        
        NDBaseContentView(
            baseConfig: baseConfig,
            navigationConfig: navigationConfig
        ) {
            VStack(spacing: 15.0) {
                topTabView
                    .padding(.horizontal, 16)
                
                NDRefreshableScrollView(
                    refreshController: refreshController,
                    onRefresh: {
                        viewModel.loadOrderList()
                    }
                ) {
                    ScrollView {
                        VStack(spacing: 15.0) {
                            Image(WJAppEnvironment.shared.currentCountry == .india ? "order_list_banner" : "order_list_banner_id")
                                .resizable()
                                .scaledToFit()
                                .hidden(viewModel.productListModel?.pachist?.isEmpty ?? true)
                            VStack(spacing: 12) {
                                ForEach(Array((viewModel.productListModel?.pachist ?? []).enumerated()), id: \.offset) { index, model in
                                    NDOrderListItem(model: model)
                                        .onTapGesture {
                                            if let schemeLink = model.mathbagfication,
                                               !schemeLink.isEmpty {
                                                if schemeLink.hasPrefix("http") || schemeLink.hasPrefix("https") {
                                                    goToWebView(schemeLink)
                                                } else {
                                                    NDSchemeManager.shared.handleURL(schemeLink)
                                                }
                                            }
                                        }
                                }
                            }
                            .ndEmptyState(
                                (viewModel.productListModel?.pachist?.isEmpty ?? (viewModel.errorMessage == nil ? false : true)) ? .noData : nil,
                                actionTitle: localizedString("Apply"),
                                action: {
                                    NotificationCenter.default.post(
                                        name: .schemeSwitchTab,
                                        object: nil,
                                        userInfo: [NDSchemeKeys.tabIndex: 0]
                                    )
                                    NotificationCenter.default.post(name: .schemeRefreshHome, object: nil)
                                }
                            )
                        }
                        .padding(.horizontal, 16)
                        .padding(.bottom, 55)
                    }
                }
            }
            .onAppear {
                if viewModel.productListModel == nil {
                    refreshController.beginRefreshing()
                }
            }
            .onChange(of: viewModel.isLoading) { isLoading in
                DispatchQueue.main.async {
                    if isLoading {
                        NDProgressHUD.show()
                    } else {
                        NDProgressHUD.dismiss()
                        refreshController.endRefreshing()
                    }
                }
            }
            .onChange(of: viewModel.refresh) { refresh in
                if refresh {
                    refreshController.beginRefreshing()
                }
            }
            .onReceive(NotificationCenter.default.publisher(for: .schemeRefreshOrderList)) { _ in
                refreshController.beginRefreshing()
            }
        }
    }
    
    func goToWebView(_ urlString: String) {
        let webUrlStr = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
        print("webUrlStr: \(webUrlStr ?? "")")
        navManager.wrappedValue.pushView(tag: mainNav) {
            NDWebView(urlString: webUrlStr,
                      isFollowOrder: false,
                      isPresent: false)
        }
    }
}

extension NDOrderContentView {
    var topTabView: some View {
        Group {
            HStack(spacing: 0) {
                ForEach(orderTabs, id: \.self) { type in
                    Button(action: {
                        viewModel.orderDataType = type
                    }) {
                        Text(type.title)
                            .font(.system(size: 14, weight: .medium))
                            .foregroundColor(viewModel.orderDataType == type ? Color(hex: "#FFFFFF") : Color(hex: "#666666"))
                            .padding(.vertical, 8)
                            .frame(maxWidth: .infinity)
                            .background(viewModel.orderDataType == type ? Color(hex: "#FD632B") : Color.clear)
                            .cornerRadius(20)
                    }
                }
            }
            .padding(5)
            .background(Color(hex: "#FFFFFF"))
            .clipShape(Capsule())
        }
    }
}
